$(function() {
    layui.use(['table', 'dropdown','form'], function(){
        var table = layui.table,
            form = layui.form ,
            $ = layui.$;
        let str = '',myUSP=[];
        $('#projectId').attr("disabled", true);
        AjaxGet('/userAunt/seleProject').then(function (response){
            str += `<option value="">请选择</option>`;
            myUSP=response.data
            response.data.map(function (v){
                str += `<option value="${v.id}">${v.name}</option>`
            });
            $("#projectId").html(str)
            $('#projectId').attr("disabled", false);
            form.render('select');
        }).catch(function (error){
            layer.msg(error.msg)
        })
        // 创建渲染实例
        table.render({
            elem: '#exampleTable'
            ,id:'exampleTable'
            ,method:"get"
            ,contentType: 'application/x-www-form-urlencoded'
            // ,contentType: 'application/json'
            ,url: "/userDemand/backgroundList"
            ,cellMinWidth: 80
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , curr: pages //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , limit : 15
                , limits : [15,30,50,100,200]
            }
            ,request:{
                pageName: 'current',
                limitName: 'size'
            }
            ,where: {
                title:$("#title").val(),
                userName:$("#userName").val(),
                projectId:$("#projectId").val(),
                status:$("#status").val(),
            }
            ,defaultToolbar: false
            ,loading: false
            ,cols: [[
                {
                    field : 'title',
                    title : '标题',
                    align : 'center'
                },
                {
                    field : 'userName',
                    title : '发布人',
                    align : 'center',
                    templet:(d)=>{return`<span>${d.userName}</span>`}
                },
                {
                    field : 'orderPhone',
                    title : '联系方式',
                    width:100,
                    align : 'center'
                },
                {
                    field: 'projectName',
                    title: '需求类型',
                    align: 'center',
                    // width:240,
                    templet: function (d) {
                        let projectId = d.projectId;
                        if ( projectId != null ){
                           let mylist= myUSP.find(item=>item.id==projectId)
                            return `
							<span>${mylist.name}</span>
							`;
                        }else{
                            return '-';
                        }
                    }
                },
                {
                    field : 'status',
                    title : '当前状态',
                    align : 'center',
                    width:100,
                    templet : function( d ) {
                        if (d.status == 1) {
                            return '<span class="label label-primary">未接单</span>';
                        } else if (d.status == 2) {
                            return '<span class="label label-warning">已接单</span>';
                        }else {
                            return '<span class="label label-warning">-</span>';
                        }
                    }
                },
                {
                    field : 'createTime',
                    title : '发布时间',
                    width:200,
                    align : 'center'
                },
                {
                    title : '操作',
                    field : 'id',
                    align : 'center',
                    width:160,
                    templet : function(d) {
                        var e = '<a  class="btn btn-primary btn-sm '+s_info_h+' " href="#" mce_href="#" title="详情" onclick="lookInfo(\''
                            + d.id
                            + '\')"><i class="fa fa-send"></i></a> ';

                        var b2 = '<a  class="btn btn-primary btn-sm '+s_edit_h+' " href="#" mce_href="#" title="编辑" onclick="edit(\''
                            + d.id
                            + '\')"><i class="fa fa-edit"></i></a> ';

                        var ss = '<a class="btn btn-success btn-sm '+s_remove_h+' " href="#" title="删除"  mce_href="#" onclick="remove(\''
                            + d.id
                            + '\')"><i class="fa fa-remove"></i></a>';
                        return  b2 +  e  + ss;
                    }
                }
            ]]
            ,response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
                if( res.code != 0 ){

                    return false;
                }

                if(Number(res.data.total)>0&&res.data.records.length==0){
                    pages--;
                    if(pages>0) {
                        table.reload('exampleTable', {
                            page: {curr: pages},
                            where: {
                                title:$("#title").val(),
                                userName:$("#userName").val(),
                                projectId:$("#projectId").val(),
                                status:$("#status").val(),
                            }
                        })
                    }
                }

                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            ,jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    pages = obj.curr
                }
            }
            ,error: function(res, msg){

            }

            ,done: function (res){
                form.render()
                hindLoading()
            }
        });

        var $ = layui.$, active = {
            reload: function(){
                //执行重载
                table.reload('exampleTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        title:$("#title").val(),
                        userName:$("#userName").val(),
                        projectId:$("#projectId").val(),
                        status:$("#status").val(),
                    }
                });
            }
        };

        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        //触发表格复选框选择
        table.on('checkbox(test)', function(obj){
            console.log(obj)
        });

        //触发表格单选框选择
        table.on('radio(test)', function(obj){
            console.log(obj)
        });

    });
});

var pages = 1;
/**
 * 所有的重置表格
 */
function load(){
    layui.use(['table'], ()=>{
        layui.table.reload('exampleTable',{
            where: {
                title:$("#title").val(),
                userName:$("#userName").val(),
                projectId:$("#projectId").val(),
                status:$("#status").val(),
            }
        })
    })
}

function lookInfo(id){
    let toIndex= layer.open({
        type: 2,
        title:'后台需求详情',
        maxmin: true,
        shadeClose: false,
        area:['800px','500px'],
        content:  `/jzweb/jazUserDemand/backstage/info/infor/${id}`
    });
    layer.full(toIndex);
}
function edit(id){
    let toIndex= layer.open({
        type: 2,
        title:'后台需求编辑',
        maxmin: true,
        shadeClose: false,
        area:['800px','500px'],
        content:  `/jzweb/jazUserDemand/backstage/info/edit/${id}`
    });
    layer.full(toIndex);
}
const add=()=>{
   let toIndex= layer.open({
        type: 2,
        title: '新增需求',
        maxmin: true,
        shadeClose: false,
        area:['800px','500px'],
        content: `/jzweb/jazUserDemand/backstage/info/add/1`,
    });
    layer.full(toIndex);
}

function remove(id) {

    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : '/userDemand/backgroundRemove',
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    load();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}